angular.module("myApp",[]).controller("cartController",function($scope){
	$scope.cart = [
	{
		id:1000,
		name:"iphone5s",
		quantity:3,
		price:1000
	},
	{
		id:3300,
		name:"iphone5",
		quantity:30,
		price:3300
	},
	{
		id:232,
		name:"imac",
		quantity:4,
		price:23000
	},
	{
		id:1300,
		name:"ipad",
		quantity:5,
		price:6900
	}
	];
	/**
	 * 计算总价
	 */
	$scope.totalPrice = function(){
		var total = 0;
		angular.forEach($scope.cart,function(item){
			total += item.quantity * item.price;
		});
		return total;
	}
	/**
	 * 计算总数量 
	 */
	$scope.totalQuantity = function(){
		var total =0;
		angular.forEach($scope.cart,function(item){
			total += parseInt(item.quantity);
		});
		return total;
	}
	/**
	 * 根据id来找key
	 */
	var findIndex = function(id){
		var index = -1;
		angular.forEach($scope.cart,function(item,key){
			if(item.id ===id){				
				index = key;
				return
			}			
		});
		return index;
		
	}
	/**
	 * 移除某一商品
	 */
	$scope.remove = function(id){
		var index = findIndex(id);
		
		if(index != -1){
			$scope.cart.splice(index,1);
		}
		
	}
	
	/**
	 * 增加数量 
	 */
	$scope.add = function(id){
		var index = findIndex(id);
		$scope.cart[index].quantity++;
	}
	
	/**
	 * 减少数量 
	 */
	$scope.reduce = function(id){
		var index = findIndex(id);
		--$scope.cart[index].quantity;
	}
	
	
	/**
	 * 监视自动做脏检查
	 */	
	$scope.$watch("cart",function(newValue,oldValue){
		angular.forEach(newValue,function(item,key){
			if(item.quantity < 1){
				var returnKey = confirm("确定改变？？");
				if(returnKey){
					$scope.remove(item.id);
				}else{
					item.quantity = oldValue[key].quantity;
				}
			}
		});
	},true);
	
	
	
	
});